﻿using Entity;
using Entity.Sale;
using ServiceCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Customer.Bussiness_Service
{ 
    public interface Iwork_service
    {
        /// <summary>
        /// 请求工单列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel<get_work_order_details_pagelist_showlisForwork> get_workorder_listForWork(get_work_order_details_pagelist_params query);
        /// <summary>
        ///  接单
        /// </summary>
        /// <param name="work_order_id"></param>
        /// <returns></returns>
        ResultModel work_get_order(string work_order_id);
        /// <summary>
        /// 更改生产状态
        /// </summary>
        /// <param name="work_order_id"></param>
        /// <param name="workstate"></param>
        /// <returns></returns>
        ResultModel change_work_state(string work_order_id, work_state? workstate);
    }
    public class work_service: Iwork_service
    {
        private readonly IToole_DI _tool;

        public work_service(IToole_DI Tool)
        {
            _tool = Tool;
        }
        /// <summary>
        ///  
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel<get_work_order_details_pagelist_showlisForwork> get_workorder_listForWork(get_work_order_details_pagelist_params query)
        {
            return CoreStartDo.ResultAction<ResultListModel<get_work_order_details_pagelist_showlisForwork>>(result =>
            {
                if (!query.posttype.HasValue)
                {
                    result.code = 1;
                    result.msg = "参数不完全 无法确认请求类型";
                    return result;
                }

                string core_sql = $"select d.u_name,{string.Join(',', _tool.search_workorder_Item)} from sale_work_order_details a left JOIN sale_work_order b on a.work_order_id = b.work_order_id left join slot_template c on a.slot_template_id = c.template_id left join rk_user d on b.add_uid = d.uid";
                string where = "where 1=1";
                dynamic query_dy = new System.Dynamic.ExpandoObject();

                where += " and work_uid=@work_uid";
                query_dy.work_uid = _tool.di_user.USER.uid;

                if (query.posttype.Value == 0)
                {
                    //只显示审核通过的订单
                    where += " and total_state=@total_state";
                    query_dy.total_state = sale_work_state_enum.审批完成;
                }
                else if (query.posttype.Value == 1)
                {
                    if (query.work_state.HasValue)
                    {
                        where += " and total_state=@work_state";
                        query_dy.work_state = query.work_state;

                    }
                    else
                    {
                        //只显示审核通过的订单
                        where += " and total_state>=@start_total_state and total_state<=@end_total_state";
                        query_dy.start_total_state = sale_work_state_enum.生产已接单;
                        query_dy.end_total_state = sale_work_state_enum.生产退回;
                    }
                } 
                if (!string.IsNullOrWhiteSpace(query.uid))
                {
                    where += " and b.add_uid=@sale_uid";
                    query_dy.sale_uid = query.uid;
                }
                if (!string.IsNullOrWhiteSpace(query.baseusername))
                {
                    where += " and  b.baseusername like @baseusername";
                    query_dy.baseusername = $"%{query.baseusername}%";
                }
                if (!string.IsNullOrWhiteSpace(query.mchname))
                {
                    where += " and  b.mch_name like @mchname";
                    query_dy.mchname = $"%{ query.mchname}%";
                }
                if (!string.IsNullOrWhiteSpace(query.work_order_details_id))
                {
                    where += " and  a.work_order_details_id like @work_order_details_id";
                    query_dy.work_order_details_id = $"%{query.work_order_details_id}%";
                }
                //if (query.work_approval_state.HasValue)
                //{
                //    where += " and  b.work_approval_state=@work_approval_state";
                //    query_dy.work_approval_state = query.work_approval_state;
                //}
                //if (query.work_state.HasValue)
                //{
                //    where += " and  b.work_state=@work_state";
                //    query_dy.work_state = query.work_state;
                //}
                if (!string.IsNullOrWhiteSpace(query.start_time))
                {
                    where += " and  b.work_end_time>=@start_time";
                    query_dy.start_time = query.start_time;
                }
                if (!string.IsNullOrWhiteSpace(query.end_time))
                {
                    where += " and  b.work_end_time<=@end_time";
                    query_dy.end_time = query.end_time;
                }
                ResultListModel<get_work_order_details_pagelist_showlisForwork> result_pagelist = _tool.di_db.GetPageList<get_work_order_details_pagelist_showlisForwork>(core_sql, where, "b.create_order_time", query_dy, query.IsPage, query.page, query.pagesize, "desc");
                if (result_pagelist.rows.Any())
                {
                    //获取机器SN以及iccid
                    string searchsql = "select a.id,a.SN,b.iccid from mch a left join SimBoss_BindMch b on a.Id = b.MchID where a.Id in @mchids";
                    List<search_sn> getsn = _tool.di_db.Get_rk_List<search_sn>(searchsql, new { mchids = result_pagelist.rows.Select(s => s.mch_id).ToArray() }).ToList();
                    foreach (var item in result_pagelist.rows)
                    {
                        var info = getsn.Where(s => s.id == item.mch_id).FirstOrDefault();
                        if (info != null)
                        {
                            item.sn = info.SN;
                            item.iccid = info.iccid;
                        }
                    }
                }
                return result_pagelist;
            });
        }
        /// <summary>
        /// 接单
        /// </summary>
        /// <returns></returns>
        public ResultModel work_get_order(string work_order_id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(work_order_id))
                {
                    result.code = 1;
                    result.msg = "缺少关键参数";
                    return result;
                }
                var work_order = _tool.di_db.GetList<sale_work_order>("select top 1 * from sale_work_order where work_order_id=@work_order_id", new { work_order_id }).FirstOrDefault();
                if (work_order == null)
                {
                    result.code = 1;
                    result.msg = "生产单不存在";
                    return result;
                }
                if (work_order.total_state != sale_work_state_enum.审批完成)
                {
                    result.code = 1;
                    result.msg = $"当前生产单{work_order.total_state.ToString()} 不允许接单";
                    return result;
                }
                if (_tool.di_user.USER.role_id != "Work_Manager" && _tool.di_user.USER.role_id != "Finance_Manager")
                {
                    result.code = 1;
                    result.msg = "非生产主管不允许接单";
                    return result;
                }
                //更新审核状态为已完成
                int ur = _tool.di_db.do_Execute("update sale_work_order set total_state=@total_state,work_state=@work_state,work_get_time=@work_get_time where work_order_id=@work_order_id", new
                {
                    total_state = sale_work_state_enum.生产已接单, //审核完成 
                    work_state = work_state.生产已接单,
                    work_order.work_order_id,
                    work_get_time = DateTime.Now//设置生产接单时间, 
                });
                if (ur > 0)
                {
                    result.code = 0;
                    result.msg = "接单成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "接单成功";
                }
                return result;
            });
        }
        /// <summary>
        /// 更改生产状态
        /// </summary>
        /// <returns></returns>
        public ResultModel change_work_state(string work_order_id, work_state? workstate)
        {
            return CoreStartDo.ResultAction(result =>
            { 
                if (!workstate.HasValue)
                {
                    result.code = 1;
                    result.msg = "请选择工作状态";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(work_order_id))
                {
                    result.code = 1;
                    result.msg = "缺少关键参数";
                    return result;
                }
                var work_order = _tool.di_db.GetList<sale_work_order>("select top 1 * from sale_work_order where work_order_id=@work_order_id", new { work_order_id }).FirstOrDefault();
                if (work_order == null)
                {
                    result.code = 1;
                    result.msg = "生产单不存在";
                    return result;
                }
                if (work_order.total_state != sale_work_state_enum.审批完成)
                {
                    if (work_order.total_state < sale_work_state_enum.生产已接单 && work_order.total_state >= sale_work_state_enum.生产退回)
                    {
                        result.code = 1;
                        result.msg = $"当前生产单{work_order.total_state.ToString()} 不允许修改生产状态";
                        return result;
                    }
                } 
                if (_tool.di_user.USER.role_id != "Work_Manager" && _tool.di_user.USER.role_id != "Finance_Manager")
                {
                    result.code = 1;
                    result.msg = "非生产主管不允许修改状态";
                    return result;
                }
                ///如果当前状态是退回 需要判断当前退回的机器是否全部解绑了
                if (workstate == work_state.生产退回)
                {
                    List<Mch_bind_record> bind_data = _tool.di_db.Get_rk_List<Mch_bind_record>("select * from Mch_bind_record where Type_id=10 and work_order_id=@work_order_id", new
                    {
                        work_order_id = work_order.work_order_id
                    }).ToList();
                    if (bind_data.Count() > 0)
                    {
                        result.code = 1;
                        result.msg = $"当前机器存在已绑定的生产单，请解绑后再进行退回操作,柜体码=>{string.Join(',', bind_data.Select(s => s.box_code))}";
                        return result;
                    }
                }
                string changetime = "";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                query_dy.total_state = workstate.Value;
                query_dy.work_state = workstate.Value;
                query_dy.work_order_id = work_order.work_order_id;
                switch (workstate)
                {
                    case work_state.生产退回:
                        query_dy.work_back_time = DateTime.Now;
                        changetime = "work_back_time";
                        break; 
                    case work_state.生产关闭:
                        query_dy.work_close_time = DateTime.Now;
                        changetime = "work_close_time";
                        break;
                    case work_state.生产完成:
                        query_dy.true_work_end_time = DateTime.Now;
                        changetime = "true_work_end_time";
                        break;
                    case work_state.生产中:
                        query_dy.working_time = DateTime.Now;
                        changetime = "working_time";
                        break;
                    case work_state.质检完成:
                        query_dy.QA_end_time = DateTime.Now;
                        changetime = "QA_end_time";
                        break;
                }
                //更新审核状态为已完成
                int ur = _tool.di_db.do_Execute($"update sale_work_order set total_state=@total_state,work_state=@work_state,{changetime}=@{changetime} where work_order_id=@work_order_id", query_dy);
                if (ur > 0)
                {
                    result.code = 0;
                    result.msg = "修改成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "修改成功";
                } 
                return result;
            });
        }
    }
}
